<?php

function dirList ($directory) {
    // ************************** //
    $badfiles = array(".DS_Store", ".", "..");

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't in the bad list,
        // add it to the results array
        if (!in_array($file, $badfiles))
            $results[] = $file;
    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

}


$updateBg  = isset($_POST['updateBg']);
$updateObj = isset($_POST['updateObj']);


if($updateBg) {
    $bgDirectory = "../bg/pics";
    $myfile = '../bg/nextBG.txt';

    // get the filename to link to
    $fh = fopen($myfile, 'r');
    //echo "" . filesize($myfile);

    $filename = fread($fh, filesize($myfile));
    fclose($fh);

    // update the symlink
    //unlink("../currentBg");
    //symlink("bg/pics/$filename", "../currentBg");
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    $tosend = mb_convert_encoding($filename, "UTF-32", "auto");
    socket_sendto($socket, $tosend, strlen($tosend), MSG_DONTROUTE, 'localhost', 50003);
    socket_close($socket);

    // write a random file path to nextBG.txt
    $files = dirList($bgDirectory);
    $fh = fopen($myfile, 'w') or die("can't open file");
    $index = rand(0, count($files)-1);
    $stringData = "" . $files[$index];
    fwrite($fh, $stringData);
    fclose($fh);
}

if($updateObj) {
    $objDirectory = "../obj/pics";
    $myfile = '../obj/nextObj.txt';

    // get the filename to link to
    $fh = fopen($myfile, 'r');
    $filename = fread($fh, filesize($myfile));
    fclose($fh);

    //unlink("../currentObj");
    //symlink("obj/pics/$filename", "../currentObj");
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    $tosend = mb_convert_encoding($filename, "UTF-32", "auto");
    socket_sendto($socket, $tosend, strlen($tosend), MSG_DONTROUTE, 'localhost', 50004);
    socket_close($socket);

    // write a random file path to nextObj.txt
    $files = dirList($objDirectory);
    $fh = fopen($myfile, 'w') or die("can't open file");
    $index = rand(0, count($files)-1);
    $stringData = "" . $files[$index];
    fwrite($fh, $stringData);
    fclose($fh);
}


?>

<html>
    <body bgcolor="yellow">

        <br>
        <form method="post">
        <input type="submit"
        style="height: 40%; font-size: 450%; width: 100%; background-color: red;"
        value="Next Background" onclick="submit">
        <input type="hidden" name="updateBg" value="1">
        </form>
        <form method="post">
        <input type="submit"
        style="height: 40%; font-size: 450%; width: 100%; background-color: red;"
        value="Next Object" onclick="submit">
        <input type="hidden" name="updateObj" value="1">
        </form>

    </body>
</html> 
